/*
 * Copyright (c) 2002-2003 by OpenSymphony
 * All rights reserved.
 */
package org.jackysoft.opensymphony.workflow.entity;

import java.io.PrintWriter;
import java.util.HashMap;
import java.util.Iterator;
import java.util.Map;

import org.jackysoft.util.XmlUtils;

/**
 * Desrives a function that can be applied to a workflow step.
 * 
 * 
 */

public class FunctionDescriptor extends AbstractDescriptor {
	// ~ Instance fields
	// ////////////////////////////////////////////////////////

	/**
	 * 
	 */
	private static final long serialVersionUID = -8461850143615384403L;

	protected Map args = new HashMap();

	/**
	 * The name field helps the editor identify the condition template used.
	 */
	protected String name;
	protected String type;

	// ~ Constructors
	// ///////////////////////////////////////////////////////////

	/**
     * 
     */
	public FunctionDescriptor() {
	}

	public FunctionDescriptor(org.dom4j.Element element) {
		super(element);this.init(element);
	}

	// ~ Methods
	// ////////////////////////////////////////////////////////////////

	public Map getArgs() {
		return args;
	}

	public void setName(String name) {
		this.name = name;
	}

	public String getName() {
		return name;
	}

	public void setType(String type) {
		this.type = type;
	}

	public String getType() {
		return type;
	}

	public void writeXML(PrintWriter out, int indent) {
		XmlUtils.printIndent(out, indent++);
		out.println("<function "
				+ (hasId() ? ("id=\"" + getId() + "\" ") : "")
				+ (((name != null) && (name.length() > 0)) ? ("name=\""
						+ XmlUtils.encode(getName()) + "\" ") : "") + "type=\""
				+ type + "\">");

		Iterator iter = args.entrySet().iterator();

		while (iter.hasNext()) {
			Map.Entry entry = (Map.Entry) iter.next();
			XmlUtils.printIndent(out, indent);
			out.print("<arg name=\"");
			out.print(entry.getKey());
			out.print("\">");

			if ("beanshell".equals(type) || "bsf".equals(type)) {
				out.print("<![CDATA[");
				out.print(entry.getValue());
				out.print("]]>");
			} else {
				out.print(XmlUtils.encode(entry.getValue()));
			}

			out.println("</arg>");
		}

		XmlUtils.printIndent(out, --indent);
		out.println("</function>");
	}

	protected void init(org.dom4j.Element function) {
		type = function.attributeValue("type");

		try {
			setId(Integer.parseInt(function.attributeValue("id")));
		} catch (NumberFormatException e) {
		}

		if (function.attributeValue("name") != null) {
			name = function.attributeValue("name");
		}

		for (Iterator argItr = function.elementIterator("arg"); argItr
				.hasNext();) {
			org.dom4j.Element argEle = (org.dom4j.Element) argItr.next();
			this.args.put(argEle.attributeValue("name"), argEle.getText());
		}
	}

	/**
	 * 
	 */
	public void setArgs(Map args) {
		this.args = args;
	}
}
